<template>
  <div class="user-avator-dropdown"  style="color: #fff">

    <Icon
      type="md-desktop"
      size="14"
      class="operation-label"
      v-show="this.showBI && !this.timeFlag"
    />
    <router-link class="operation-title mr-25" to="/bi" v-show="this.showBI && !this.timeFlag"
      >企业看板</router-link
    >
    <Icon type="ios-home" size="16" class="operation-label" v-show="!this.timeFlag"/>
    <span class="operation-title mr-25" @click="toIndex" v-show="!this.timeFlag">工作首页</span>
    <Dropdown
      trigger="click"
      @on-visible-change="getInfo"
      transfer
      :transfer-class-name="transferClassName"
    >

      <Badge class="operation-title mr-4" :dot="!!messageUnreadCount" >
        <span class="header_options_user" v-show="timeFlag">
           <img src="../../../../../src/assets/images/bi/user.png" alt="">
           <i class="current-date">{{currentDate}}</i>
        </span>
        <span v-show="!timeFlag">您好，欢迎{{ userName }}</span>

      </Badge>
      <Icon :size="14" type="ios-arrow-down"></Icon>
      <DropdownMenu slot="list">
        <DropdownItem style="white-space: normal !important">
          <Row>
            <Col span="6">
              <img
                :src="fileUploadUrl + '/file/downFile/' + this.userInfo.avatar"
                v-if="this.userInfo.avatar"
                height="50"
                width="50"
                style="border-radius: 25px;"
              />
              <img
                :src="userImage"
                v-if="!this.userInfo.avatar"
                height="50"
                width="50"
                style="border-radius: 25px;"
              />
            </Col>
            <Col span="18">
              <p class="user-name">{{ this.userInfo.name }}/{{ this.userInfo.userName }}</p>
              <p class="user-poster" style="word-break: break-all">{{ this.depPost }}</p>
              <p class="user-poster">{{ this.userInfo.orgName }}</p>
            </Col>
          </Row>
        </DropdownItem>
        <DropdownItem
          divided
          v-show="
            this.userInfo.otherIdentityList.length > 0 &&
              userType != 'ADMIN_USER'
          "
        >
          <Row>
            <Col span="6">
              <span>切换身份</span>
            </Col>
            <Col span="18">
              <ul>
                <li
                  class="user-li"
                  v-for="(item, index) in this.userInfo.otherIdentityList"
                  :key="index"
                  @click="changeOrg(item, index)"
                >
                  <Button size="small" long>
                    {{ item.name }}
                  </Button>
                </li>
              </ul>
            </Col>
          </Row>
        </DropdownItem>
        <DropdownItem divided>
          <Row justify="center">
            <Col span="12" class="user-center">
              <a @click="changePass">修改密码</a>
            </Col>
            <Col span="12" class="user-center">
              <a @click="logout">退出登录</a>
            </Col>
          </Row>
        </DropdownItem>
      </DropdownMenu>
    </Dropdown>
    <Modal v-model="modal" :class="{'user-bi-modal':timeFlag}" title="温馨提示" @on-ok="ok">
      <p>切换身份需重新登录，确认切换？</p>
    </Modal>
    <Modal v-model="modal2" :class="{'user-bi-modal':timeFlag}" title="提醒" @on-ok="logoutForce">
      <p>密码修改成功，请用新密码重新登录。</p>
    </Modal>
    <Modal v-model="modal3" class-name="vertical-center-modal" :class="{'user-bi-modal':timeFlag}" title="修改密码">
      <div style="text-align: center">
        <input
          style="width: 250px"
          type="password"
          placeholder="请输入新密码"
          class="input1"
        />
      </div>
      <div style="text-align: center">
        <input
          class="input2"
          style="width: 250px;margin-top: 10px"
          placeholder="请再次输入新密码"
          type="password"
        />
      </div>
      <div slot="footer">
        <Button type="primary" @click="retsetPass">确定</Button>
      </div>
    </Modal>

    <Modal v-model="modal4" :class="{'user-bi-modal':timeFlag}" title="温馨提示" @on-ok="logoutForce">
      <p>确认退出登录吗？</p>
    </Modal>

  </div>
</template>

<script>
import './user.scss'
import { mapActions } from 'vuex'
import userImage from '@/assets/images/manage.png'
import CryptoJS from 'crypto-js/crypto-js'
import { getUserInLocalstorage } from '@/libs/util'
export default {
  data() {
    return {
      userInfo: {
        otherIdentityList: []
      },
      depPost: '',
      nowOrg: {},
      modal: false,
      fileUploadUrl: process.env.VUE_APP_FILE_SERVER_URL,
      user: {},
      modal2: false,
      modal3: false,
      modal4:false,
      userImage,
      showBI: true,
      currentDate: '',
      transferClassName:'user-drop'
    }
  },
  name: 'User',
  props: {
    userAvator: {
      type: String,
      default: ''
    },
    messageUnreadCount: {
      type: Number,
      default: 0
    },
    userName: {
      type: String
    },
    userType: {
      type: String
    },
	timeFlag:{
	  type: Boolean,
	  default: false
	}
  },
  created(){
    this.showRealTime();
    setInterval(()=>{
      this.showRealTime()
    },1000)
    if(this.timeFlag){
      this.transferClassName = 'user-drop bi-user';
    }
  },
  mounted() {
    this.depPost = ''
    this.$api.user.getUserInfo().then(res => {
      //获取个人信息
      this.userInfo = res.data
      res.data.deptAndPostList.forEach((item, index) => {
        let str = item.deptName + '-' + item.posts + ';'
        this.depPost += str
      })
    })
    let user = getUserInLocalstorage()
    //项目用户不展示BI看板
    this.showBI = user.userInOrgType == 'PROJECT_TEAM_USER' ? false : true
  },
  methods: {
    ...mapActions(['handleLogOut', 'ResetTags']),
    showRealTime(){
    	let d = new Date();
    	let year = d.getFullYear();
    	let month = d.getMonth() + 1;
    	let date = d.getDate();
    	let day = d.getDay();
    	let hour = (d.getHours() < 10) ? ("0" + d.getHours()) : d.getHours();
    	let min = (d.getMinutes() < 10) ? ("0" + d.getMinutes()) : d.getMinutes();
    	let sec = (d.getSeconds() < 10) ? ("0" + d.getSeconds()) : d.getSeconds();
    	// let now = year + "-" + month + "-" + date + "-" + hour + ":" + min + ":" + sec;
    	let now = hour + ":" + min + ":" + sec;
    	this.currentDate = now;
    },
    logout() {

      if(this.timeFlag){
        this.modal4 = true
      }else{
        this.$Modal.confirm({
          title: '温馨提示',
          closable: true,
          content: '确认退出登录吗？',
          width: 360,
          onOk: () => {
            this.logoutForce()
          }
        })
      }

    },
    logoutForce() {
      this.$api.user.logoutRecord().then(({ code, message }) => {
        if (200 === code) {
          //登出做记录
          this.modal2 = false
          this.handleLogOut().then(() => {
            this.ResetTags()
            this.$router.push({
              name: 'login'
            })
          })
        } else {
          this.$Message.error(message)
        }
      })
    },
    toIndex() {
      this.$router.push({
        name: 'work'
      })
    },
    getInfo(visible) {
      if (visible) {
        //如果展开个人信息的话
        this.depPost = ''
        this.$api.user.getUserInfo().then(res => {
          //获取个人信息
          this.userInfo = res.data
          res.data.deptAndPostList.forEach((item, index) => {
            let str = item.deptName + '-' + item.posts + ';'
            this.depPost += str
          })
        })
      }
    },
    ok() {
      let params = {
        personId: this.nowOrg.personId,
        name: this.nowOrg.name,
        personUserOrgIdList: this.nowOrg.personUserOrgIdList
      }
      this.$api.user.logoutRecord().then(res => {
        //登出记录
        this.$api.user.editRightCorner(params).then(res => {
          this.handleLogOut().then(() => {
            this.$router.push({
              name: 'login'
            })
          })
        })
      })
    },
    changeOrg(item, index) {
      window.event ? (window.event.cancelBubble = true) : e.stopPropagation()
      // window.console.log(item)
      // if (!this.nowOrg.personId) {
      //   this.nowOrg = item
      // }
      // if (
      //   this.nowOrg.name !== item.name
      // ) {
      //   this.modal = true
      this.nowOrg = item
      this.modal = true
    },
    changePass() {
      this.modal3 = true
    },
    retsetPass() {
      let oldPass = document.getElementsByClassName('input1')[0].value
      let newPass = document.getElementsByClassName('input2')[0].value
      if (oldPass && newPass) {
        if (oldPass == newPass) {
          if (!this.$regex.passWordReg(newPass)) {
            this.$Message.warning(
              '密码只能6-16位字符的数字、英文字母（区分大小写）组合，其他特殊字符不可以使用'
            )
          } else {
            let params = {
              newPassword: this.encrypt(newPass)
            }
            this.$api.user.resetPass(params).then(res => {
              if (res.code == 200) {
                this.modal3 = false
                this.showReLoad()
              } else {
                this.$Message.info(res.message)
              }
            })
          }
        } else {
          this.$Message.warning('密码必须一致')
        }
      } else {
        this.$Message.warning('请填写密码')
      }
    },
    showReLoad() {
      this.modal2 = true
    },
    encrypt(word) {
      //加密
      var key = CryptoJS.enc.Utf8.parse('AZB_AES_PASSWORD')
      var srcs = CryptoJS.enc.Utf8.parse(word)
      var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      return encrypted.toString()
    }
  }
}
</script>
<style lang="scss" scoped>
.operation-label {
  margin-right: 5px;
}
.operation-title {
  font-size: 12px;
  color: #fff;
}
.mr-25 {
  margin-right: 25px;
}
.mr-4 {
  margin-right: 4px;
}

</style>
